﻿using Efcore_Test.Entities;
using Efcore_Test.Services.Dtos;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.AspNetCore.Mvc;
using static Volo.Abp.UI.Navigation.DefaultMenuNames.Application;

namespace Efcore_Test.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AccountController : AbpController
    {
        private readonly UserManager<MyUser> _userManager;
        private readonly SignInManager<MyUser> _signInManager;

        public AccountController(UserManager<MyUser> userManager, SignInManager<MyUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        [Authorize()]
        [HttpGet("Viart")]
        public async void Viart()
        {
            var data = await _userManager.GetUserAsync(User);
            var x = User;
        }

        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterDto dto)
        {
            var user = new MyUser { UserName = dto.Email, Email = dto.Email, NickName = dto.NickName, PasswordHash = dto.Password };
            var result = await _userManager.CreateAsync(user, dto.Password);

            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, isPersistent: false);
                return Ok("注册成功");
            }
            return BadRequest(result.Errors);
        }

        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginDto dto)
        {
            var result = await _signInManager.PasswordSignInAsync(dto.Email, dto.Password, isPersistent: false, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                return Ok("登录成功");
            }
            return Unauthorized("登录失败");
        }

        [HttpPost("logout")]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return Ok("已退出登录");
        }
    }
}
